package com.plug.common.spring.utils;

import org.springframework.core.io.support.PropertiesLoaderSupport;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.Properties;

/**
 * 属性配置工具类
 *
 * @author Archx[archx@foxmail.com]
 * @date 2016/3/11 0011
 */
public class PropertyConfigurer extends PropertiesLoaderSupport {

    private static Properties properties;

    public static String getValue(String key) {
        if (properties == null) {
            throw new IllegalArgumentException("未使用Spring加载配置文件.");
        }
        return properties.getProperty(key);
    }

    public static String getValue(String key, String defaultValue) {
        String value = getValue(key);
        return StringUtils.hasText(value) ? value : defaultValue;
    }

    /**
     * 初始化方法
     *
     * @throws IOException
     */
    public void init() throws IOException {
        synchronized (PropertyConfigurer.class) {
            if (properties == null) {
                PropertyConfigurer.properties = mergeProperties();
            }
        }
    }

}
